﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace passitumi
{
	/**
	 * This class will manage the gui component for the preferences
	 * window. This window contains information regarding the client's
	 * name, download location and eventually additional functions.
	 */
	public partial class PreferencesGui : Form
	{

		private PreferenceManager preferences = MainApplication.preferences;
		/**
		 * Constructor which initializes the window frame component.
		 */
		public PreferencesGui()
		{
			InitializeComponent();

			downloadFilePathTextBox.Text = preferences.getDownloadFilePath();
			displayNameTextBox.Text = preferences.getDisplayName();

			this.okButton.Enabled = false;

			this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.closePreferencesWindow);
		}

		/**
		 * Open a window for the user to browse for a folder where incoming
		 * files will be placed.
		 */
		private void browseForDownloadFilePath()
		{
			FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
			folderBrowser.Description = "Select folder to place downloads";

			if (folderBrowser.ShowDialog() == DialogResult.OK)
			{
				downloadFilePathTextBox.Text = folderBrowser.SelectedPath;
			}
		}

		/**
		 * Respond to the browse button being clicked.
		 */
		private void browseButtonClick(object sender, EventArgs e)
		{
			this.browseForDownloadFilePath();
		}

		/**
		 * Handler for when the apply button has been clicked.  On this event we want to apply
		 * the changes that have been made to passitumi settings, and then close the window.
		 */
		private void okButtonClick(object sender, EventArgs e)
		{
			this.applySettingChanges();
			this.closePreferencesWindow(null, null);
		}

		private void unsavedSettingChangeOccurred(object sender, EventArgs e)
		{
			this.okButton.Enabled = true;
		}

		/**
		 * Update the local preference settings to what the user has entered in the form.
		 */
		protected void applySettingChanges()
		{
			downloadFilePathTextBox.Text = downloadFilePathTextBox.Text.Trim();
			displayNameTextBox.Text = displayNameTextBox.Text.Trim();

			preferences.updateDownloadFilePath(downloadFilePathTextBox.Text);

			if (displayNameTextBox.Text.Length != 0)
				preferences.updateDisplayName(displayNameTextBox.Text);

			preferences.savePreferences();
		}

		/**
		 * Close the window.
		 */
		protected void closePreferencesWindow(object sender, FormClosingEventArgs args)
		{
			this.FormClosing -= closePreferencesWindow;
			this.Close();
		}
	}
}
